package com.haojiang.mh.remote.ui.dialog

import android.graphics.Color
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import cn.com.heaton.blelibrary.ble.utils.ThreadUtils
import com.haojiang.mh.R
import com.haojiang.mh.remote.adapter.BleSingleDialogFragAdapter
import com.haojiang.mh.remote.base.BaseDialogFrag
import com.haojiang.mh.remote.bean.BleRssiDevice
import com.haojiang.mh.remote.bean.DeviceModifySuccessEvent
import com.haojiang.mh.remote.callback.IBleItemClickLisenter
import com.haojiang.mh.remote.enums.EConnect
import com.haojiang.mh.remote.enums.EStep
import com.haojiang.mh.remote.event.BleEvent
import com.haojiang.mh.remote.event.BleStatus
import com.haojiang.mh.remote.event.ConnectEvent
import com.haojiang.mh.remote.event.SurfaceEvent
import com.haojiang.mh.remote.utils.BleUtil
import com.haojiang.mh.remote.utils.BleUtil.Companion.ble
import com.haojiang.mh.remote.utils.BleUtil.Companion.bleRssiDeviceList
import com.haojiang.mh.remote.utils.BleUtil.Companion.devDisconnectAll
import com.haojiang.mh.remote.utils.BleUtil.Companion.devScan
import com.haojiang.mh.remote.utils.BleUtil.Companion.lastConnect
import com.haojiang.mh.remote.utils.Util
import com.haojiang.mh.remote.utils.Util.Companion.checkBleStatus
import kotlinx.android.synthetic.main.frag_dialog_ble_single.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*


class BleSingleDialogFrag : BaseDialogFrag() {

    /**
     * 伴生函数
     */
    companion object {

        val instance by lazy {
            BleSingleDialogFrag()
        }

        fun show(fragmentActivity: FragmentActivity) {
            val fm = fragmentActivity.supportFragmentManager
            fm.executePendingTransactions()
            fm.beginTransaction().detach(instance)
            fm.beginTransaction().remove(instance)

            if (instance.isAdded) {
                instance.dismiss()
            }
            instance.show(
                fragmentActivity.supportFragmentManager,
                BleSingleDialogFrag::class.java.simpleName
            )

        }
    }

    private val bleSingleDialogFragAdapter by lazy {
        BleSingleDialogFragAdapter(
            activity!!,
            bleRssiDeviceList
        )
    }

    /**
     * 点击后回调并连接ble设备
     */
    private var iOnBleItemClickLisenter = object : IBleItemClickLisenter {
        override fun onClick(bleDeviceList: ArrayList<BleRssiDevice>, connectType: Int) {
            if (!checkBleStatus(context!!)) return
            ble.stopScan()  //停止扫描
            when (connectType) {
                EConnect.CONNECT_TEST.data -> {
                    BleUtil.devConnects(bleDeviceList)
                }
                EConnect.CONNECT_SINGLE.data -> {
                    //单机连接  初始化最后一次连接信息
                    EventBus.getDefault().post(
                        ConnectEvent(
                            EStep.STEP_CLICK_CONNECT.data,
                            EConnect.CONNECT_SINGLE.data,
                            0L,
                            bleDeviceList
                        )
                    )
                }
            }


//            prepareConnect(bleDeviceList)
//            val interfaceNo = readInterfaceNo()
//            if (TextUtils.isEmpty(interfaceNo)) {
//                SelectDialogFrag.show(activity!!)
//            } else {
//                val funList = SurfaceUtil.map.get(interfaceNo.substring(0, 4).toUpperCase(Locale.ROOT))
//                if (funList != null) {
//                    if (funList.size > 0) {
//                        dismiss()
//                        devConnects(context!!, lastBleDeviceList)
//                        EventBus.getDefault().post(FunctionEvent(funList))
//                    }
//                }
//            }
//                devConnects(context!!, bleDeviceList, GROUP_TYPE_NONE, 0L)
//            }
        }
    }


    override fun onSubCreate(savedInstanceState: Bundle?) {
        setStyle(STYLE_NO_TITLE, R.style.fragment_dialog_fullscreen)
//        groupType = arguments!!.getInt(GROUP_TYPE)
//        groupId = arguments!!.getLong(GROUP_ID)
//        LogUtil.e(groupType.toString() + "-----" + groupId)
    }


    override fun onSubCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        EventBus.getDefault().register(this)
        return inflater.inflate(R.layout.frag_dialog_ble_single, container, false)
    }

    override fun onSubViewCreated(view: View, savedInstanceState: Bundle?) {
        dialog!!.setCancelable(true)                                                                                                //是否可以点击取消
        dialog!!.setCanceledOnTouchOutside(true)                                                                        //dialog外面是否可以点击

        val params = dialog!!.window!!.attributes
        context?.let {
            //            if (groupType == GROUP_TYPE_NONE) {
//            if (lastGroupType == GROUP_TYPE_NONE) {
//                params.width = (Util.getScreenWidth(context) * 0.85f).toInt()
//            } else {
//                params.width = LinearLayout.LayoutParams.MATCH_PARENT
//            }
            params.width = (Util.getScreenWidth(it) * 0.85f).toInt()
            params.height = LinearLayout.LayoutParams.MATCH_PARENT
            params.gravity = Gravity.RIGHT
            //高度自己定义
            dialog!!.window!!.setLayout(params.width, params.height)
        }
    }


    override fun onSubActivityCreated(savedInstanceState: Bundle?) {
        bleSingleDialogFragAdapter.iOnBleItemClickLisenter = iOnBleItemClickLisenter
//        bleDialogFragAdapter.groupType = groupType
//        bleDialogFragAdapter.viewList.clear()
        rvControl.addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL))
        rvControl.layoutManager = LinearLayoutManager(context)
        rvControl.itemAnimator = null
        rvControl.adapter = bleSingleDialogFragAdapter

//        when (groupType) {
//        when (lastGroupType) {
//            GROUP_TYPE_NONE -> {
//                ivGroupType.visibility = View.INVISIBLE
//            }
//            GROUP_TYPE_SINGLE -> {
//                ivGroupType.visibility = View.VISIBLE
//                ivGroupType.setImageResource(R.drawable.ic_group_single_n)
//            }
//            GROUP_TYPE_MULTIPLE -> {
//                ivGroupType.visibility = View.VISIBLE
//                ivGroupType.setImageResource(R.drawable.ic_group_multiple_n)
//            }
//            GROUP_TYPE_SPLIT -> {
//                ivGroupType.visibility = View.VISIBLE
//                ivGroupType.setImageResource(R.drawable.ic_group_split_n)
//            }
//        }

        //初始化刷新控件
        swipeRefreshLayout.setColorSchemeColors(Color.RED, Color.YELLOW, Color.GREEN)
        //刷新监听
        swipeRefreshLayout.setOnRefreshListener {
            activity?.let {
                if (!checkBleStatus(activity!!)) {
                    swipeRefreshLayout.isRefreshing = false
                } else {
//                    if (groupType != GROUP_TYPE_NONE) {
                    if (lastConnect.connectType != EConnect.CONNECT_SINGLE.data) {
                        devDisconnectAll()
                    }
                    if (ble.isBleEnable) {
                        ThreadUtils.submit {
                            devScan()
                        }
                    } else {
                        swipeRefreshLayout.isRefreshing = false
                    }
                }
            }
        }

        //返回按键
        ivBack.setOnClickListener(object : View.OnClickListener {
            override fun onClick(v: View?) {
                dismiss()
            }
        })

        //如果是单一设备隐藏保存按钮
//        if (groupType == GROUP_TYPE_NONE) {
//        if (lastGroupType == GROUP_TYPE_NONE) {
//            tvSave.visibility = View.INVISIBLE
//        } else {  //组类型显示按钮
//            tvSave.visibility = View.VISIBLE
//            tvSave.setOnClickListener(object : View.OnClickListener {
//                override fun onClick(v: View?) {
//                    val groupValueList = bleDialogFragAdapter.getSelectList()
//                    if (groupValueList.size > 0) {
////                        if (BleUtil.addGroupValueList(context!!, groupId, groupValueList)) {
//                        if (BleUtil.addGroupValueList(context!!, lastGroupId, groupValueList)) {
//                            dismiss()
////                            devDisconnectAll()
//                            val bleDeviceList = ArrayList<BleRssiDevice>()
//                            groupValueList.forEach {
//                                bleDeviceList.add(it.bleRssiDevice)
//                            }
////                            devConnects(context!!, bleDeviceList, groupType, groupId)
//                            devConnects(context!!, bleDeviceList)
////                            EventBus.getDefault().post(AddGroupEvent(groupId, true))
//                            EventBus.getDefault().post(AddGroupEvent(true))
//                        }
//                    } else {
//                        showToast(AppContext.getInstance().getString(R.string.m_selection_can_not_be_empty))
//                    }
//                }
//            })
//        }
        devScan()
    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    fun onDeviceModifyEvent(event: DeviceModifyEvent) {
//        if (event.className.equals(BleControlDialogFrag::class.java.simpleName)) {
//        ModifyDialogFrag.show(activity!!, event.className,  event.bleRssiDevice.bleAddress, event.bleRssiDevice.bleName, event.bleRssiDevice.deviceAlias!!)
//        }
//    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onDeviceModifySuccessEvent(event: DeviceModifySuccessEvent) {
//        if (event.className.equals(BleControlDialogFrag::class.java.simpleName)) {
        bleSingleDialogFragAdapter.modifyItem(event.bleAddress, event.deviceAlias)
//        }
    }

    /**
     * 界面功能已经刷新并关闭当前界面
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onFunctionEvent(event: SurfaceEvent) {
        dismiss()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onBleEvent(event: BleEvent) {
        when (event.devStatus) {
            BleStatus.SCAN_PREPARE -> {
                bleRssiDeviceList.clear()
//                bleDialogFragAdapter.initData(groupType)
                bleSingleDialogFragAdapter.initData()        //初始化蓝牙列表dapter
                if (!swipeRefreshLayout.isRefreshing) {
                    swipeRefreshLayout.isRefreshing = true
                }
            }

            BleStatus.SCAN_RSSI_CHANGED -> {
                val data = event.data
                if (data != null) {
//                    bleControlDialogFragAdapter.dataRssiRefresh()
                    bleSingleDialogFragAdapter.notifyItemChanged(data.toInt())
                }
            }

            BleStatus.SCAN_FOUND -> {
//                bleDialogFragAdapter.dataRefresh()
                bleSingleDialogFragAdapter.notifyDataSetChanged()
            }

            BleStatus.SCAN_STOP -> {
//                bleControlDialogFragAdapter.dataRefresh()
                swipeRefreshLayout?.let {
                    if (swipeRefreshLayout.isRefreshing) {
                        swipeRefreshLayout.isRefreshing = false
                    }
                }
            }


            BleStatus.GATT_SERVICE_CONNECT -> {
//                val bleDevice = event.bleDevice
//                if (bleDevice != null) {
//                    if (!MotorTestDialogFrag.instance.isAdded) {
//                        MotorTestDialogFrag.show(activity!!)
//                    }
//                }

//                val bleDevice = event.bleDevice
//                if (bleDevice != null) {

//                    ThreadUtils.ui(Runnable {
////                        if (groupType == GROUP_TYPE_NONE) {
//                        if (lastGroupType == GROUP_TYPE_NONE) {
//                            //如果是内置蓝牙QRRM跳入选择界面
//                            if (bleDevice.bleName.substring(0, 4).equals(Constant.QRRM, true)) {
//                                dialog?.dismiss()
////                                val localInterface = BleUtil.readLocalInterface(bleDevice.bleAddress)       //读取本地界面
//                                val localInterface = SpUtil.getData(context, SECTION_GROUP_ID, bleDevice.bleAddress, "") as String      //读取本地界面
//                                if (TextUtils.isEmpty(localInterface) || bleDevice.bleName.startsWith(QRRM)) {
////                                    activity?.let { it -> SelectDialogFrag.show(it) }
//                                    SelectDialogFrag.show(activity!!)
//                                } else {
//                                    getFunction(localInterface)
//                                }
//                            } else {
//                                getFunction(bleDevice.bleName)
//                            }
//                        } else {
////                            MotorDialogFrag.show(activity!!, groupType)
//                            MotorDialogFrag.show(activity!!)
//                        }
//                    })
//                }
            }
        }
    }


//    private fun getFunction(bleName: String) {
//        val funList = SurfaceUtil.map.get(bleName.substring(0, 4).toUpperCase())
//        //如果界面的功能列表不存在
//        if (funList == null) {
//            showToast(getString(R.string.m_interface_not_exist))    //提示界面不存在断开连接
////            BleUtil.devDisconnect()
//        } else {
////            LogUtil.e("是不是加載了三次" + funList.size)
//            //如果是外置蓝牙直接广播获取的界面功能列表
//            EventBus.getDefault().post(FunctionEvent(funList))
//        }
//        dialog?.hide()
//    }

    override fun initDestroy() {
        ble.stopScan()
        EventBus.getDefault().unregister(this)
    }

}